﻿using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.Entities.BPM_Process;
using NP.BPMReportPlatform.FlowManagement;
using NP.BPMReportPlatform.FlowManagement.Dto;
using NP.BPMReportPlatform.RecurringJobs.Dto.FlowManager;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.RecurringJobs
{
    /// <summary>
    /// 流程催办接口应用Job
    /// </summary>
    public class FlowUrgingRecurringJob : BpmReportPlatformRecurringJob, IFlowUrgingRecurringJob
    {
        private readonly SqlSugarClient _dbBusiness, _dbEngine, _dbProcess;
        private readonly IFlowManagementAppService _flowManagementAppService;
        private ILogger _logger;
        public FlowUrgingRecurringJob(ISqlSugarAppService sqlSugarAppService, IConfiguration configuration, IFlowManagementAppService flowManagementAppService, ILogger logger)
        {
            _dbBusiness = sqlSugarAppService.GetBusinessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _dbProcess = sqlSugarAppService.GetProcessInstance();
            _flowManagementAppService = flowManagementAppService;
            _logger = logger;
        }

        /// <summary>
        /// 自动催办逾期未处理的流程
        /// </summary>
        public async Task AutoFlowUrgingOverdueAsync()
        {
            int week = (int)DateTime.Now.DayOfWeek;//星期几,星期天是0
            int day = DateTime.Now.Day;//多少号
            int lastDay = DateTime.Now.AddMonths(1).AddDays(-DateTime.Now.Day).Day;//获取当前月最后一天
            var hour = DateTime.Now.Hour;
            //获取待催办的流程配置信息
            var FlowUrgingList = await _dbBusiness.Queryable<FlowUrgingConfiguration>().Where(x => x.IsDelete == false && x.FlowUrgingType== "1").ToListAsync();
            
            foreach (var item in FlowUrgingList)
            {
                
                if (!item.Weeks.IsNullOrWhiteSpace())
                {
                    var isUrgngWeek = item.Weeks.Split(',').Distinct().ToList().Where(w=>w==week.ToString()).ToList();
                    if (isUrgngWeek.Count == 0)
                    {
                        continue;//跳过不满足按照星期几来催办的流程
                    }
                }
                if (!item.Days.IsNullOrWhiteSpace())
                {
                    var isUrgngDay = item.Days.Split(',').Distinct().ToList().Where(w => w == day.ToString()).ToList();
                    if (isUrgngDay.Count == 0)
                    {
                        if(day==lastDay && !item.Days.Contains("31"))
                        {
                            //特殊配置31号，表示每月最后一天会催办
                        }
                        else
                        {
                            continue;//跳过不满足按照催办日来催办的流程
                        }
                       
                    }

                }
                if (item.TimeSlot == "早中")
                {
                    //一天催办两次，早上和中午都催办
                }
                else
                {
                    if (hour < 12 && item.TimeSlot == "中午")
                    {
                        continue; //跳过中午催办的流程
                    }
                    else if (hour >= 12 && (item.TimeSlot == "早上" || item.TimeSlot.IsNullOrWhiteSpace()))
                    {
                        continue; //跳过早上催办的流程
                    }
                }
               
                var query = _dbEngine
               .Queryable<Instances, InstanceStates>((it, its) => it.InstanceId == its.InstanceId)
               .Where((it, its) => its.Status == 1)
               .WhereIF(!string.IsNullOrWhiteSpace(item.BTID), (it, its) => it.BTID == item.BTID)
               .WhereIF(!string.IsNullOrWhiteSpace(item.NodeName), (it, its) => its.LatestActivityName == item.NodeName)
               .WhereIF(!string.IsNullOrWhiteSpace(item.ExpiryDate.ToString()), (it, its) => its.LatestArriveTime.Value.AddDays(+item.ExpiryDate) < DateTime.Now)
               .Select((it, its) => new
               {
                   InstanceNumber = it.Number,
                   LatestArriveTime = its.LatestArriveTime
               }).ToList();

                FlowUrgingInput input = new FlowUrgingInput();
                if (query.Any())
                {
                    foreach(var item2 in query)
                    {
                        if (!item.Frequency.IsNullOrWhiteSpace())
                        {
                            var diffDays = DateTime.Now.Subtract(item2.LatestArriveTime.Value.AddDays(+item.ExpiryDate)).Days;//今天与第一次逾期相差天数
                            var pp = int.Parse(item.Frequency);// 频率
                            var remainder = diffDays % pp;// 取余
                            if (remainder != 0) 
                            { 
                                continue; 
                            }
                        }
                        if (!item2.InstanceNumber.IsNullOrWhiteSpace())
                        {
                            input.InstanceNumber = item2.InstanceNumber;
                            await Task.Delay(2000);//延迟2秒 催办
                            await _flowManagementAppService.FlowUrgingAsync(input);
                        }
                    }  
                }     
            }
        }
        /// <summary>
        /// 自动催办逾期未处理的流程(依赖书)
        /// 试线结果反馈定时提醒。有入库记录开始的第7天开始提醒【试线结果反馈】节点进行结案，频率每隔7天
        /// </summary>
        public async Task AutoFlowUrgingTo1Async()
        {
            string instanceId ="";
            try
            {
                //获取待催办的流程配置信息
                var FlowUrgingList = await _dbBusiness.Queryable<FlowUrgingConfiguration>().Where(x => x.IsDelete == false && x.FlowUrgingType == "2").ToListAsync();
                foreach (var item in FlowUrgingList)
                {
                    List<string> query1 = await _dbEngine.Queryable<Instances, InstanceStates>((it, its) => it.InstanceId == its.InstanceId)
                   .Where((it, its) => its.Status == 1)
                   .WhereIF(!string.IsNullOrWhiteSpace(item.BTID), (it, its) => it.BTID == item.BTID)
                   .WhereIF(!string.IsNullOrWhiteSpace(item.NodeName), (it, its) => its.LatestActivityName == item.NodeName)
                   .WhereIF(!string.IsNullOrWhiteSpace(item.ExpiryDate.ToString()), (it, its) => its.LatestArriveTime.Value.AddDays(+item.ExpiryDate) < DateTime.Now)
                   .Select(it => it.Number
                   ).ToListAsync();
                    if (query1.Any())
                    {
                        _logger.Information("催办逾期未处理的依赖书流程");
                        //查询入库记录开始的第7天的流程
                        var query2 = await _dbBusiness.Queryable<TechnicalDependenceTrial>()
                            .Where(t => query1.Contains(t.InstanceNumber))
                            .WhereIF(!string.IsNullOrWhiteSpace(item.ExpiryDate.ToString()), t => Convert.ToDateTime(t.CreateTime).AddDays(+item.ExpiryDate) < DateTime.Now)
                            .ToListAsync();
                        FlowUrgingInput input = new FlowUrgingInput();
                        if (query2.Any())
                        {
                            foreach (var item2 in query2)
                            {
                                instanceId = item2.InstanceNumber;
                                //获取最新的回数
                                var trialTimes = await _dbBusiness.Queryable<TechnicalDependenceDetail2>().Where(d => d.InstanceNumber == item2.InstanceNumber).MaxAsync(d => d.TrialTimes);
                                if (!item2.Times.IsNullOrWhiteSpace() && !trialTimes.IsNullOrWhiteSpace())
                                {
                                    if (!item2.InstanceNumber.IsNullOrWhiteSpace() && int.Parse(item2.Times) == int.Parse(trialTimes))
                                    {
                                        input.InstanceNumber = item2.InstanceNumber;
                                        await _flowManagementAppService.FlowUrgingAsync(input);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Information("催办逾期未处理的依赖书流程失败：" + instanceId+ ";"+ e.Message.ToString());
                throw e;
            }
           
        }
    }
}
